package com.googlecode.struts2scope.context;

import java.util.HashMap;
import java.util.Map;

import com.googlecode.struts2scope.scope.ScopeType;

public class FlashContext extends ContextImpl {

	private static final String KEY = ScopeType.class.getName() + "_" + ScopeType.FLASH.name();

	private final Map<String, Object> request;

	private Map<String, Object> session;

	public FlashContext(Map<String, Object> session, Map<String, Object> request) {
		super(request);
		this.session = session;
		this.request = request;
		if (getCurrentFlash() == null) {
			renew();
		} else {
			dumpToRequest();
		}
	}

	public Object removeAttribute(String name) {
		throw new UnsupportedOperationException();
	}

	public void setAttribute(String name, Object value) {
		getCurrentFlash().put(name, value);
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> getCurrentFlash() {
		return (Map<String, Object>) session.get(KEY);
	}

	private void dumpToRequest() {
		Map<String, Object> currentFlash = getCurrentFlash();
		for (Map.Entry<String, Object> entry : currentFlash.entrySet()) {
			request.put(entry.getKey(), entry.getValue());
		}
	}

	public void renew() {
		session.put(KEY, new HashMap<String, Object>());
	}
}
